import Singleton from "./Singleton";
import GameEvent from '../event/GameEvent';
import Data from "./Data";
const wx = window["wx"] || window["tt"];

const { ccclass, property } = cc._decorator;

export default class WXTTUtils extends Singleton {

    public LoginServerWxOrTT(callback: Function) { //仅拿取用户openid
        if (Data.user.openid) {
            GameEvent.Instance().dispatch("SDK_LOGIN_SUCC");
            return;
        }
        if (cc.sys.os == cc.sys.OS_WINDOWS) {
            Data.user.openid = WXTTUtils.guid();
            cc.log("window 授权成功")
            GameEvent.Instance().dispatch("SDK_LOGIN_SUCC");
            return;
        } else {
            wx.login({
                success: (e) => {
                },
                fail: () => {
                }
            })
        }
    }

    static createAuthorizeBtn(btnNode: cc.Node, callback: Function): any {
        let p = btnNode.parent.convertToWorldSpaceAR(btnNode.position);
        let btnSize = cc.size(btnNode.width, btnNode.height);
        let winSize = cc.director.getWinSize();
        //获取系统信息的宽度
        let sysInfo = wx.getSystemInfoSync();
        let screenW = sysInfo.screenWidth;
        let screenH = sysInfo.screenHeight;
        let rate = screenW / winSize.width;//设计分辨率为750*1334
        let width = btnSize.width * rate;
        let height = btnSize.height * rate;
        let left = screenW / 2 + ((p.x - screenW) * rate - width / 2);
        let top = screenH / 2 - ((p.y - screenH) * rate + height / 2);
        var wxButton = wx.createUserInfoButton({
            type: 'text',
            text: '',
            style: {
                left: left,
                top: top,
                width: width,
                height: height,
                lineHeight: 20,
                backgroundColor: '',
                color: '#FFFFFF',
                textAlign: 'center',
                fontSize: 16,
                borderRadius: 4
            }
        });
        wxButton.onTap(() => {
            callback();
        });
        return wxButton;
    }

    //用于生成uuid
    private static S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    static guid() {
        var uid = cc.sys.localStorage.getItem("uid");
        if (!uid) {
            uid = (this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4());
            cc.sys.localStorage.setItem("uid", uid);
        }
        return uid;
    }
    static jump(appid): void {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.navigateToMiniProgram({
                appId: appid,
                path: '',
                extraData: null,
                envVersion: 'release',
                success(res) {
                    console.log('跳转成功');
                }
            })
        }
    }
}